<?php 
namespace app\controllers;

use Yii;
use yii\web\Controller;
use yii\web\Response;

//新建一个class类，里面放有注册，登录，展示，删除的方法
class CurdController extends Controller{
        public function actionRegister(){

        	//接值
        	$post=Yii::$app->request->post();
        	//把接到的值放到数组里
        	if (!empty($post)) {
        		$data=[
                 'name'=>$post['name'],
                 'pwd'=>md5($post['pwd']) ,
                 'phone'=>$post['phone'],
        		];
               if ($data) {
               	Yii::$app->db->createCommand()->insert("user",$data)->execute();
              echo "<script> var sure=confirm( '注册成功，要立即登录吗?'); if (1==sure){alert( '您选择了立即登录')} else {alert( '你选择了取消登录 ');location.href='?r=curd/register'}</script>";
                return $this->render('login');
               	exit;
               }
               else
               {
               	echo "<script>alert('注册失败');location.href='index.php?r=/curd/register'</script>";
               }
        	}
        	//渲染模板
        	return $this->render('register');
        }
        public function actionLogin()
        {
        	//接值
        	$name=Yii::$app->request->post('name');
        	$pwd=Yii::$app->request->post('pwd');

        	//写查询的SQL语句
        	$sql="SELECT * FROM user WHERE name='$name' AND pwd='$pwd'";
        	$res=Yii::$app->db->createCommand($sql)->query();
        	if ($res) {
        		echo "<script>alert('登录成功');location.href='?r=/curd/show'</script>";
        		
        	}
        	else
        	{
        		echo "<script>alert('登录失败');location.href='?r=/curd/login'</script>";
        	}
        }
        public function actionShow()
        {
        	//写查询的SQL语句
        	$sql="SELECT * FROM user";
        	$data=Yii::$app->db->createCommand($sql)->query();
        	//渲染模板
        	return $this->render('show',['data'=>$data]);
        }
        public function actionDel()
        {
        	//接值
        	$id=Yii::$app->request->get('id');

        	//写查询的SQL语句
        	$sql="DELETE FROM user WHERE id='$id'";
        	$res=Yii::$app->db->createCommand($sql)->execute();
        	if ($res) {
        		echo "<script>alert('删除成功');location.href='?r=/curd/show'</script>";
        		exit;
        		
        	}
        	else
        	{
        		echo "<script>alert('删除失败');location.href='?r=/curd/login'</script>";
        	}
        }
}
